﻿/*
 * Разработчик: Коледа Андрей
 * Дата: 20.01.2011
 * Время: 11:12
 * Email: koleda.andrey@gmail.com
 */
using System;
using System.Security.Cryptography;
using System.Web.Configuration;
using System.Web.Security;

namespace FastTravel.Utilites
{
	/// <summary>
	/// Управление паролями
	/// </summary>
	public class PasswordHelper
	{
		private const string CONFIG_KEY_PWD = "HashPasswords";
		private const string HASH_ALGORITHM_FOR_PASSWORDS = "SHA1";
		private const int SALT_LENGTH = 16;

		/// <summary>
		/// Хэширование пароля
		/// </summary>
		/// <param name="password">Пароль</param>
		/// <param name="passwordSalt">Ключ</param>
		/// <returns></returns>
		public static string HashPassword(string password, string passwordSalt)
		{
			bool useHash = false;
			try
			{
				useHash = bool.Parse(WebConfigurationManager.AppSettings.Get(CONFIG_KEY_PWD));
			}
			catch (SystemException)
			{
			}
			return useHash
					   ? FormsAuthentication.HashPasswordForStoringInConfigFile(passwordSalt + password, HASH_ALGORITHM_FOR_PASSWORDS)
					   : password.PadRight(40);
		}

		/// <summary>
		/// Генератор ключей
		/// </summary>
		/// <returns>Ключ</returns>
		public static string GeneratePasswordSalt()
		{
			var rng = new RNGCryptoServiceProvider();
			byte[] salt = new byte[SALT_LENGTH];
			rng.GetBytes(salt);

			return Convert.ToBase64String(salt);
		}

	}

}